package com.socket.learing.transfer;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;

@Slf4j
public class DatagrameClient implements Runnable {

    private short port;

    public DatagrameClient(short port) {
        this.port = port;
    }

    @Override
    public void run() {
        try (DatagramSocket datagramClient = new DatagramSocket();) {
            ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[512]);
            byteBuffer.putShort(port);
            DatagramPacket datagramPacket = new DatagramPacket(byteBuffer.array(), byteBuffer.limit());
            datagramPacket.setAddress(InetAddress.getByName("255.255.255.255"));
            datagramPacket.setPort(CommonConstant.SERVICE_DATAGRAM_PORT);
            datagramClient.send(datagramPacket);
            log.info("消息发送完成");

            ByteBuffer responseBuffer = ByteBuffer.wrap(new byte[512]);
            DatagramPacket response = new DatagramPacket(responseBuffer.array(), responseBuffer.limit());
            datagramClient.receive(response);

            InetAddress service = response.getAddress();
            int port = responseBuffer.getInt();
            log.info("消息回送IP：{},回送端口：{}", service, port);
        } catch (SocketException e) {
            log.error("socket异常：{}", e);
        } catch (UnknownHostException e) {
            log.error("host异常：{}", e);
        } catch (IOException e) {
            log.error("IO异常：{}", e);
        }
    }

}